package com.mall.pay.mq;

import com.alibaba.fastjson.JSON;
import com.mall.pay.model.PayLog;
import com.mall.pay.service.IPayLogService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author Darren
 * @date 2022-09-13 15:05
 * Description：
 */
@Component
@RocketMQTransactionListener(txProducerGroup = "rocket")
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayLogService payLogService;

    /**
     * 发送prepare消息成功后回调该方法用于执行本地事务
     *
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            // =====本地事务开始=====
            String result = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            PayLog payLog = JSON.parseObject(result, PayLog.class);
            payLogService.addPayLog(payLog);
            // =====本地事务结束=====
        } catch (Exception e) {
            // 异常，消息回滚
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 消息回查
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return RocketMQLocalTransactionState.COMMIT;
    }
}
